package com.itheima.health.service.impl;

import com.itheima.health.dao.ReportDao;
import com.itheima.health.dao.SetmealDao;
import com.itheima.health.dto.HotSetmeal;

import com.itheima.health.dto.MemberVO;
import com.itheima.health.dto.SetmealCount;
import com.itheima.health.dto.SetmealVO;
import com.itheima.health.pojo.Business;
import com.itheima.health.pojo.Order;
import com.itheima.health.service.ReportService;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private ReportDao reportDao;
    @Autowired
    private SetmealDao setmealDao;
    @Override
    public MemberVO getMemberReport() {
        //获取当前年月日
        LocalDate nowDate = LocalDate.now();
        String[] months = new String[12];
        String[] memberCount = new String[12];
        int i = 0;
        for (
            //当前月减去11
                LocalDate month = nowDate.minusMonths(11);
            //获取到当前月份为止
                month.isBefore(nowDate.plusMonths(1));
            //每次月份+1
                month = month.plusMonths(1)) {
            Date date = Date.from(month.atStartOfDay(ZoneId.systemDefault()).toInstant());
            //获取指定月份前一共有多少会员
            Integer count = reportDao.countByMonth(date);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            months[i] =sdf.format(date);
            memberCount[i] = count == null ? "0" : "" + count;
            i++;
        }
        return new MemberVO(months, memberCount);
    }

    @Override
    public SetmealVO getSetmealReport() {
        List<SetmealCount> setmealCounts=reportDao.SelectSetmealInfo();
        String[] names = new String[setmealCounts.size()];
        for (int i = 0; i < setmealCounts.size(); i++) {
            names[i] = setmealCounts.get(i).getName();
        }

        return new SetmealVO(names,setmealCounts);

    }

    @Override
    public Business getBusinessReportData() {
        Business business = new Business();
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String format = sdf.format(date);
        //1.获取热门套餐信息
        //热门套餐
        List<HotSetmeal> hotSetmeal = new ArrayList<>();
        Integer[] setmealId=reportDao.SelectSetmealId();//(1,2)
        Integer AllOrderNumber=reportDao.SelectOrderNumber();//所有订单数量
        for (Integer integer : setmealId) {
            HotSetmeal hotSetmeal1 = new HotSetmeal();
            Integer SetmealNum=reportDao.SelectSetmealNum(integer);
            String setmealName = setmealDao.selectName(integer);
            Double proportion = (SetmealNum * 1.0 / AllOrderNumber) *100;
            hotSetmeal1.setName(setmealName);
            hotSetmeal1.setSetmeal_count(SetmealNum);
            String proportion1=proportion.toString()+"%";
            hotSetmeal1.setProportion(proportion1);
            hotSetmeal.add(hotSetmeal1);
        }
        business.setHotSetmeal(hotSetmeal);

        //2.赛日期
        business.setReportDate(format);
        //3.新增会员数
        Integer todayNewMember=reportDao.SelectTodayNewMember(date);
        business.setTodayNewMember(todayNewMember);
        //4.总会员数
        Integer totalMember=reportDao.selectTotalMember();
        business.setTotalMember(totalMember);
        //5.本月新增会员数
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
        Date firstDay = calendar.getTime();//当月的第一天
        Integer thisMonthNewMember=reportDao.SelectThisWeekNewMember(firstDay,date);
        business.setThisMonthNewMember(thisMonthNewMember);
        //6.本周新增会员数
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        // 判断要计算的日期是否是周日，如果是则减一天计算周六的，否则会出问题，计算到下一周去了
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
        if (1 == dayWeek) {
            cal.add(Calendar.DAY_OF_MONTH, -1);
        }
        cal.setFirstDayOfWeek(Calendar.MONDAY);// 设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一
        int day = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
        cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);
        Date firstDayOfWeek = cal.getTime();
        Integer thisWeekNewMember=reportDao.SelectThisMonthNewMember(firstDayOfWeek,date);
        business.setThisWeekNewMember(thisWeekNewMember);

        //7.今日预约数
        String ordertypeTelephone = Order.ORDERTYPE_TELEPHONE;
        String ordertypeWeixin = Order.ORDERTYPE_WEIXIN;
        Integer todayOrderNumber=reportDao.SelectTodayVisitsNumber(date,ordertypeTelephone,ordertypeWeixin);
        business.setTodayOrderNumber(todayOrderNumber);
        //8.今日到诊数
        String orderstatusYes = Order.ORDERSTATUS_YES;
        Integer todayVisitsNumber=reportDao.SelectTodayOrderNumber(date,orderstatusYes);
       business.setTodayVisitsNumber(todayVisitsNumber);
        //9.本周预约数
        Integer thisWeekOrderNumber=reportDao.SelectThisWeekOrderNumber(date,firstDayOfWeek);
        business.setThisWeekOrderNumber(thisWeekOrderNumber);
        //10.本周到诊数
        Integer thisWeekVisitsNumber=reportDao.SelectThisWeekVisitsNumber(date,firstDayOfWeek,orderstatusYes);
        business.setThisWeekVisitsNumber(thisWeekVisitsNumber);
        //11.本月预约数
        Integer thisMonthOrderNumber=reportDao.SelectThisMonthOrderNumber(date,firstDay);
        business.setThisMonthOrderNumber(thisMonthOrderNumber);
        //12.本月到诊数
        Integer thisMonthVisitsNumber=reportDao.SelectThisMonthVisitsNumber(date,firstDay,orderstatusYes);
        business.setThisMonthVisitsNumber(thisMonthVisitsNumber);

        return business;





    }

    @Override
    public void exportBusinessReport(HttpServletResponse response) {
        Business business=getBusinessReportData();
        // 加载文件
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/report_template.xlsx");

        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);
            XSSFSheet sheet = excel.getSheet("Sheet1");
            XSSFRow row = sheet.getRow(2);// 获取行
            XSSFCell cell = row.getCell(5); // 获取单元格
            cell.setCellValue(business.getReportDate());
            //会员数据统计
            row = sheet.getRow(4);
            row.getCell(5).setCellValue(business.getTodayNewMember());
            row.getCell(7).setCellValue(business.getTotalMember());

            row = sheet.getRow(5);
            row.getCell(5).setCellValue(business.getThisWeekNewMember());
            row.getCell(7).setCellValue(business.getThisMonthNewMember());

            //预约到诊数据统计
            row = sheet.getRow(7);
            row.getCell(5).setCellValue(business.getTodayOrderNumber());
            row.getCell(7).setCellValue(business.getTodayVisitsNumber());

            row = sheet.getRow(8);
            row.getCell(5).setCellValue(business.getThisWeekOrderNumber());
            row.getCell(7).setCellValue(business.getThisWeekVisitsNumber());

            row = sheet.getRow(9);
            row.getCell(5).setCellValue(business.getThisMonthOrderNumber());
            row.getCell(7).setCellValue(business.getThisMonthVisitsNumber());
            List<HotSetmeal> hotSetmeal = business.getHotSetmeal();
            for (int i = 0; i < hotSetmeal.size(); i++) {
                row=sheet.getRow(12+i);
                row.getCell(4).setCellValue(hotSetmeal.get(i).getName());
                row.getCell(5).setCellValue(hotSetmeal.get(i).getSetmeal_count());
                row.getCell(6).setCellValue(hotSetmeal.get(i).getProportion());
            }
            // 通过输出流将Excel文件下载到浏览器---输出流
            ServletOutputStream out = response.getOutputStream();
            // 响应头
            response.setHeader("Content-Disposition", "attachment;fileName=statistic_analysis.xlsx");
            excel.write(out);

            out.flush();
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
